package com.gitee.loyo.utils;


import com.google.common.io.BaseEncoding;
import lombok.SneakyThrows;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import static java.nio.charset.StandardCharsets.UTF_8;

public class CryptoUtils {

    @SneakyThrows
    public static String encodeByAes128_CBC_PKCS5Padding(String plaint, String initVector, String key){
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(UTF_8));
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(UTF_8), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, spec, iv);
        byte[] encrypted = cipher.doFinal(plaint.getBytes(UTF_8));
        return BaseEncoding.base64().encode(encrypted);
    }

    @SneakyThrows
    public static String decodeByAes128_CBC_PKCS5Padding(String encrypted, String initVector, String key){
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(UTF_8));
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(UTF_8), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, spec, iv);
        byte[] original = cipher.doFinal(BaseEncoding.base64().decode(encrypted));

        return new String(original);
    }
}
